<!DOCTYPE html>
<html lang="en">

<head>
    <meta charset="UTF-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Document</title>
    <style>
        * {
            margin: 0;
            padding: 0;
        }

        .box {
            position: relative;
            width: 300px;
            height: 300px;
            margin: 50px auto;
            background-color: pink;
        }

        .box>.son {
            position: absolute;
            top: 0;
            left: 0;
            width: 100px;
            height: 100px;
            background-color: skyblue;
        }
    </style>
</head>

<body>
    <div class="box">
        <div class="son"></div>
    </div>
</body>
<script>
    // 获取元素
    const box = document.querySelector('.box');
    const son = document.querySelector('.son');

    // 初始化小盒子位置
    son.style.left = `${box.clientWidth / 2 - son.offsetWidth / 2}px`;
    son.style.top = `${box.clientHeight / 2 - son.offsetHeight / 2}px`;

    // 注册事件
    document.addEventListener('keydown', function (e) {
        // 合法距离
        let diffX = box.clientWidth - son.offsetWidth;
        let diffY = box.clientHeight - son.offsetHeight;
        // 分配步长
        let stepX = diffX / 10;
        let stepY = diffY / 10;
        // 盒子边距
        let top = son.offsetTop;
        let left = son.offsetLeft;

        // 方向键键盘码 
        // 左 37 上 38 右 39 下 40

        // 左移动
        if (e.keyCode == 37) {
            left -= stepX;
            if (left < 0) left = 0;
            son.style.left = `${left}px`;
        }

        // 上移动
        if (e.keyCode == 38) {
            top -= stepY;
            if (top < 0) top = 0;
            son.style.top = `${top}px`;
        }

        // 右移动
        if (e.keyCode == 39) {
            left += stepX;
            if (left > diffX) left = diffX;
            son.style.left = `${left}px`;
        }

        // 下移动
        if (e.keyCode == 40) {
            top += stepY;
            if (top > diffY) top = diffY;
            son.style.top = `${top}px`;
        }
    });
</script>

</html>